﻿using HotelManagementClient.Utlis;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using Newtonsoft.Json;
using System.Text;
using System.Threading;

namespace HotelManagementClient.Model
{
    public class MqttClient
    {
        public delegate void MessageHandler(string msg);
        public event MessageHandler OnMessage;
        public IMqttClient m_MqttClient = null;
        public async Task MqttClientCon(List<string> topicList,string clientId)
        {
            try
            {
                if (m_MqttClient == null)
                {
                    m_MqttClient = new MqttFactory().CreateMqttClient();
                    var mqttOptions = new MqttClientOptions()
                    {
                        
                        ClientId = clientId,
                        ChannelOptions = new MqttClientTcpOptions()
                        {
                            //服务主机地址
                            Server = "gw.yglock.com",
                            Port = 1883
                        },

                        Credentials = new MqttClientCredentials()
                        {
                            Username = "user",
                            Password = Encoding.UTF8.GetBytes("mqtt_6636")

                        },
                        CleanSession = false,
                        KeepAlivePeriod = TimeSpan.FromSeconds(65535),
                        CommunicationTimeout = TimeSpan.FromSeconds(30)
                    };

                    CancellationToken cancellationToken = new CancellationToken();
                    var result = await m_MqttClient.ConnectAsync(mqttOptions, cancellationToken);

                    if (result.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
                    {
                        //订阅主题
                        foreach (var item in topicList)
                        {
                            await m_MqttClient.SubscribeAsync(new MqttTopicFilter() { Topic = item });
                        }

                        Console.WriteLine("连接成功");

                        /*var postData = new { msg = "连接成功"};
                        OnMessage(Encryptor.EncryptData(JsonConvert.SerializeObject(postData), MainWindow.des3Key));*/
                    }
                    else
                    {
                        Console.WriteLine("连接失败");
                        m_MqttClient = null;
                    }

                    //消息监听
                    m_MqttClient.UseApplicationMessageReceivedHandler(e =>
                    {
                        OnMessage(e.ApplicationMessage.ConvertPayloadToString());
                    });

                    m_MqttClient.UseDisconnectedHandler(e =>
                    {
                        Console.WriteLine("关闭成功");
                        m_MqttClient = null;
                    });
                }
            }
            catch (Exception ex)
            {
                OnMessage(ex.Message);
                m_MqttClient.Dispose();
                m_MqttClient = null;
            }
        }

        //发送消息
        public async void Send(MqttApplicationMessage applicationMessage, CancellationToken cancellationToken1)
        {

            var result1 = await m_MqttClient.PublishAsync(applicationMessage, cancellationToken1);
            if (result1.ReasonCode == MQTTnet.Client.Publishing.MqttClientPublishReasonCode.Success)
            {
                string msgStr = $"Topic:{applicationMessage.Topic}\n" +
                    $"Payload:{Encoding.UTF8.GetString(applicationMessage.Payload)}";
                Console.WriteLine(msgStr);
            }
            else
            {
                Console.WriteLine("发送失败");
            }
        }

        public async void Dispose()
        {
            if (m_MqttClient != null)
            {
                m_MqttClient.Dispose();
                m_MqttClient = null;
                Console.WriteLine("服务已关闭");
            }
        }
    }
}
